class Customer < ActiveRecord::Base
	belongs_to :customer_level
	has_one :member_card
	has_many :order_maintains, dependent: :destroy
	has_many :order_beauties, dependent: :destroy
	has_many :part_salses
	belongs_to :car_brand
	belongs_to :car_model
	belongs_to :insurer
	has_many :customer_reviews

	after_create :check_level
	after_update :check_level
	# validates_presence_of :car_brand_id
	validates_presence_of :name, :message => "姓名不能为空"
	validates_presence_of :phone, :message => "电话不能为空"
	validates_length_of :car_num, :is => 7, :message => "车牌号应为7位"
	validates_uniqueness_of :car_num ,:case_sensitive => false, :message => "车牌已存在"

	def check_level
	  if MemberCard.last.nil?
	  	code = 0.to_s.rjust(6, "0")
  	  else
  	  	code = (MemberCard.last.code.to_i + 1).to_s.rjust(6, "0")
  	  end
	  if self.customer_level_id == 2
	  	MemberCard.create(customer_id: self.id, code: code)
	  else
	  	if self.member_card
	  	  self.member_card.destroy	
	  	end
  	  end
	end
end
